<template>
  <el-card class="">
    <div slot="header" class="clearfix">
      <span>时段管理</span>
    </div>
    <el-form
      :model="form"
      ref="form"
      label-width="110px"
      :inline="false"
      size="small"
    >
      <div v-for="(item, index) in list" :key="item.id">
        <el-row>
          <el-col :span="4">
            <el-form-item>
              <div
                slot="label"
                :style="{
                  color: item.color
                }"
              >
                {{ item.pname }}(元):
              </div>
              <el-input
                placeholder="请输入电价"
                v-model="item.price"
                type="number"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="0">
            <el-form-item>
              <div
                slot="label"
                :style="{
                  color: item.color
                }"
              >
                {{ item.name }}:
              </div>
              <div class="flex-x flex-wrap">
                <div
                  v-for="(li, i) in item.children"
                  :key="li.id"
                  style="margin-right: 6px; margin-bottom: 6px; width: 40%"
                  class="flex-x"
                >
                  <!-- <el-time-picker
                    is-range
                    arrow-control
                    v-model="li.value"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    placeholder="选择时间范围"
                  >
                  </el-time-picker> -->
                  <el-time-select
                    :disabled="li.token"
                    placeholder="起始时间"
                    v-model="li.startTime"
                    :picker-options="{
                      start: '00:00',
                      step: '00:30',
                      end: '24:00'
                    }"
                  >
                  </el-time-select>
                  <span>-</span>
                  <el-time-select
                    :disabled="li.token"
                    placeholder="结束时间"
                    v-model="li.endTime"
                    :picker-options="{
                      start: li.startTime,
                      step: '00:30',
                      end: '24:00'
                    }"
                  >
                  </el-time-select>
                  <i
                    @click="handleDel(index, i, li)"
                    class="el-icon-delete"
                    style="font-size: 20px; margin-left: 6px"
                  ></i>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="4" :offset="0">
            <el-button type="primary" size="small" @click="handleAdd(index)"
              >添加</el-button
            >

            <el-button type="primary" size="small" @click="handleState(item)"
              >保存</el-button
            >
          </el-col>
        </el-row>
      </div>
    </el-form>
    <TimeIntervalColor ref="colorBox"></TimeIntervalColor>
  </el-card>
</template>

<script>
import TimeIntervalColor from "./TimeIntervalColor.vue";
import { formatDate } from "@/filter/index";
import { generateId } from "@/utils";
import { TYPES } from "../constent";
import { currentDate3, currentDate } from "@/utils/currentDate";
import {
  createElectrovalence,
  deleteElectrovalence,
  updateElectrovalence
} from "@/api/energyManage";
import _ from "lodash";
export default {
  components: { TimeIntervalColor },
  props: {
    // list: {
    //   type: Array,
    //   default: () => [1]
    // },
    tableAllData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      allColorList: [],
      colorList: [],
      form: {},
      TYPES: TYPES,
      relatedYear: "",
      peakPrice: 0,
      valleyPrice: 0,
      normalPrice: 0,
      list: [
        {
          pname: "峰时电价",
          name: "峰时区间",
          mardId: "0",
          price: "",
          color: "#A263FF",
          children: [
            {
              mardId: "0",
              color: "#A263FF",
              startTime: "",
              endTime: ""
            }
          ]
        },
        {
          pname: "谷时电价",
          name: "谷时区间",
          mardId: "1",
          price: "",
          color: "#FFC900",
          children: [
            {
              mardId: "1",
              color: "#FFC900",
              startTime: "",
              endTime: ""
            }
          ]
        },
        {
          pname: "平时电价",
          name: "平时区间",
          mardId: "2",
          price: "",
          color: "#FF0064",
          children: [
            {
              mardId: "2",
              color: "#FF0064",
              startTime: "",
              endTime: ""
            }
          ]
        }
      ]
    };
  },
  mounted() {
    let date = new Date();
    this.relatedYear = date.getFullYear();
  },
  methods: {
    handleDel(index, i, li) {
      if (li.token) {
        this.$confirm("确定删除该条数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            deleteElectrovalence(li.token).then(res => {
              this.$msg({
                type: "success",
                message: "删除成功!"
              });
              this.list[index].children.splice(i, 1);
              this.$emit("updata");
            });
          })
          .catch(err => {});
      } else {
        this.list[index].children.splice(i, 1);
      }
    },
    //保存
    async handleState(item) {
      //校验电价
      if (!item.price) {
        this.$msg({
          type: "warning",
          message: "请输入电价"
        });
        return;
      }
      let flag = false;
      //赋值电价的价区，校验时间是否完善
      item.children.forEach(res => {
        res.electrovalenceUnitPrice = item.price;
        res.mardId = item.mardId;
        if (!res.endTime || !res.startTime) {
          flag = true;
        }
      });

      if (flag) {
        this.$msg({
          type: "warning",
          message: "请完善开始时间和结束时间"
        });
        return;
      }
      //筛选出新增的数据（即没有token的数据）
      let newPrice = item.children.filter(res => !res.token);
      console.log("newPrice", newPrice);
      list = [...this.tableAllData, ...newPrice];
      //走色块方法判断是否有重合时间段
      let check = await this.drawColorBox(list, "check");
      if (check) {
        return;
      }
      //判断电价是否有变化，如果有变化的话已经存在的数据要调用编辑接口
      let priceChange = false;
      if (
        (item.mardId === "0" && item.price !== this.peakPrice) ||
        (item.mardId === "1" && item.price !== this.valleyPrice) ||
        (item.mardId === "2" && item.price !== this.normalPrice)
      ) {
        priceChange = true;
      }
      if (priceChange) {
        let editPrice = item.children.filter(res => res.token);
        let editData = await this.handleEdit(editPrice);
      }
      let data = await this.handleCreate(newPrice);
      this.$msg({
        type: "success",
        message: "保存成功"
      });
      let list = [];
      this.$emit("updata");
    },
    //调用编辑接口
    handleEdit(list) {
      return new Promise(async (resolve, reject) => {
        for (let i = 0; i < list.length; i++) {
          let params = {
            ...list[i]
          };
          await updateElectrovalence(params, params.token);
        }
        resolve();
      });
    },
    //调用创建接口
    handleCreate(list) {
      return new Promise(async (resolve, reject) => {
        for (let i = 0; i < list.length; i++) {
          let params = {
            ...list[i],
            relatedYear: this.relatedYear.toString(),
            token:
              this.relatedYear +
              "-" +
              list[i].startTime +
              "-" +
              list[i].endTime +
              "-" +
              list[i].mardId
          };
          await createElectrovalence(params);
        }
        resolve();
      });
    },
    //绘制色块并校验时间是否重合
    drawColorBox(data, check) {
      //色块数据
      this.colorList = _.cloneDeep(data);
      //无色块数据
      let unColorList = [];
      this.colorList = this.colorList.filter(
        res => res.startTime && res.endTime
      );
      //色块数据写入颜色，计算开始时间和结束时间的时间差值
      this.colorList = this.colorList.map(res => {
        if (res.mardId === "0") {
          res.color = check ? "" : "#A263FF";
        }
        if (res.mardId === "1") {
          res.color = check ? "" : "#FFC900";
        }
        if (res.mardId === "2") {
          res.color = check ? "" : "#FF0064";
        }
        let aMinutes = this.$moment(
          new Date(new Date().setHours(...res.endTime.split(":")))
        ).diff(
          new Date(new Date().setHours(...res.startTime.split(":"))),
          "minutes"
        );
        aMinutes = (aMinutes / 10).toFixed(0) * 10;
        return {
          ...res,
          startTime: new Date(new Date().setHours(...res.startTime.split(":"))),
          endTime: new Date(new Date().setHours(...res.endTime.split(":"))),
          minutes: aMinutes,
          boxNum: aMinutes / 30
        };
      });
      //色块数据重新排序
      this.colorList.sort(function(a, b) {
        let obj1 = a["startTime"];
        let obj2 = b["startTime"];
        const val1 = Math.floor(new Date(obj1).getTime() / 1000);
        const val2 = Math.floor(new Date(obj2).getTime() / 1000);
        return val1 - val2;
        // return val2 - val1
      });
      //当列表接口变化时重新渲染顶部数据
      if (!check) {
        let dateList = _.cloneDeep(this.colorList);
        console.log("我进来了", dateList);
        let peakList = [];
        let valleyList = [];
        let normalList = [];
        //分别存储峰谷平数据，及峰谷平电价
        for (let item of dateList) {
          item.startTime = formatDate(item.startTime, "HH:mm");
          item.endTime = formatDate(item.endTime, "HH:mm");
          if (item.mardId === "0") {
            this.peakPrice = JSON.parse(
              JSON.stringify(item.electrovalenceUnitPrice)
            );
            peakList.push(item);
          }
          if (item.mardId === "1") {
            this.valleyPrice = JSON.parse(
              JSON.stringify(item.electrovalenceUnitPrice)
            );
            valleyList.push(item);
          }
          if (item.mardId === "2") {
            this.normalPrice = JSON.parse(
              JSON.stringify(item.electrovalenceUnitPrice)
            );
            normalList.push(item);
          }
        }
        //将峰谷平数据存进对应条目中
        for (let i = 0; i < this.list.length; i++) {
          if (i === 0) {
            this.list[i].price = this.peakPrice;
            if (peakList.length) {
              this.list[i].children = peakList;
            }
          }
          if (i === 1) {
            this.list[i].price = this.valleyPrice;
            if (valleyList.length) {
              this.list[i].children = valleyList;
            }
          }
          if (i === 2) {
            this.list[i].price = this.normalPrice;
            if (normalList.length) {
              this.list[i].children = normalList;
            }
          }
        }
      }
      //渲染结束

      //分别取第一个时间前面的空白时间，几个时间段中间的空白时间，和最后一个时间之后的空白时间
      this.colorList.forEach((res, index) => {
        if (index === 0) {
          let usMinutes = 0;
          usMinutes = this.$moment(new Date(res.startTime)).diff(
            new Date(new Date().setHours(0, 0, 0, 0)),
            "minutes"
          );
          usMinutes = (usMinutes / 10).toFixed(0) * 10;
          if (usMinutes > 0) {
            unColorList.push({
              color: check ? "" : "#808080",
              minutes: usMinutes,
              startTime: new Date(new Date().setHours(0, 0, 0, 0)),
              endTime: new Date(res.startTime),
              boxNum: usMinutes / 30
            });
          }
        } else {
          let minutes = 0;
          minutes = this.$moment(new Date(res.startTime)).diff(
            new Date(this.colorList[index - 1].endTime),
            "minutes"
          );
          minutes = (minutes / 10).toFixed(0) * 10;
          if (minutes > 0) {
            unColorList.push({
              color: check ? "" : "#808080",
              minutes: minutes,
              startTime: new Date(this.colorList[index - 1].endTime),
              endTime: new Date(res.startTime),
              boxNum: minutes / 30
            });
          }
        }
        if (index === this.colorList.length - 1) {
          let isMinutes = 0;
          isMinutes = this.$moment(
            new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1
          ).diff(new Date(res.endTime), "minutes");
          isMinutes = (isMinutes / 10).toFixed(0) * 10;

          if (isMinutes > 0) {
            unColorList.push({
              color: check ? "" : "#808080",
              minutes: isMinutes,
              startTime: new Date(res.endTime),
              endTime: new Date(
                new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1
              ),
              boxNum: isMinutes / 30
            });
          }
        }
      });
      let allColorList = [];
      allColorList = [...this.colorList, ...unColorList];
      //将空白时间和峰谷平时间重新整合排序
      allColorList.sort(function(a, b) {
        let obj1 = a["startTime"];
        let obj2 = b["startTime"];
        const val1 = Math.floor(new Date(obj1).getTime() / 1000);
        const val2 = Math.floor(new Date(obj2).getTime() / 1000);
        return val1 - val2;
        // return val2 - val1
      });
      let sec = 0;
      allColorList.forEach(res => {
        sec += res.minutes;
      });
      //一天一共1440分钟，超过1440分钟说明有重合时间的数据，需要进行优化
      if (sec <= 1440) {
        this.allColorList = allColorList;
        this.$refs.colorBox.getColorData(this.allColorList);
        return false;
      } else {
        this.$msg({
          type: "error",
          message: "存在重合时段,请重新选择"
        });
        return true;
      }
    },
    handleAdd(index, i) {
      this.list[index].children.push({
        color: "",
        startTime: "",
        endTime: ""
        // id: generateId()
      });
    }
  }
};
</script>

<style scoped lang="scss"></style>
